package com.zklock;

import org.I0Itec.zkclient.ZkClient;

import java.util.concurrent.CountDownLatch;

/**
 * Created by yu756 on 2020/4/2 0:07
 */
public abstract class ZkAbstractTemplateLook implements ZKLock {

    public static final String ZKSERVER = "192.168.0.107:2181";
    public static final int TIME_OUT = 45 * 1000;
    public String path = "/zklock0402";
    public CountDownLatch countDownLatch = null;
    ZkClient zkClient = new ZkClient(ZKSERVER, TIME_OUT);

    public void zklock() {
        if (tryZkLock()) {
            System.out.println(Thread.currentThread().getName() + "\t 占用锁成功");
        } else {
            waitZkLock();
            zklock();
        }

    }

    public abstract boolean tryZkLock();

    public abstract boolean waitZkLock();

    public void zkUnlock() {


        if (ZKSERVER != null) {
            zkClient.close();
        }
        System.out.println(Thread.currentThread().getName() + "\t 释放锁成功");
        System.out.println();
        System.out.println();
    }
}
